﻿using System.Collections.Generic;
using UnityEngine;

namespace GameDesigner
{
    public abstract class StateMachineView : MonoBehaviour
    {
        public StateController controller;
#if STATE_MACHINE_OLD
        public StateMachine stateMachine;
#endif
#if UNITY_EDITOR
        //[HideInInspector]
        public StateMachine editStateMachine;
        internal int editStateMachineId = -1;
        public Object animClipReference;
#endif
        public virtual Transform Parent { get; }

        public virtual void Init(params object[] args)
        {
        }

        public virtual void OnDestroy()
        {
            foreach (var layer in controller.layers)
                layer.stateMachine.OnDestroy();
        }

#if UNITY_EDITOR
        public void OnValidate()
        {
            OnScriptReload();
        }

        public virtual void OnScriptReload()
        {
            if (controller == null)
                return;
            if (controller.layers == null)
                controller.layers = new StateLayer[0];
            if (controller.layers.Length <= 0)
            {
                var layer = controller.AddNewLayer("Base Layer");
                layer.Weight = 1f;
            }
            controller.View = this;
#if STATE_MACHINE_OLD
            if (stateMachine != null && stateMachine.States.Length != 0)
            {
                controller.layers[0].stateMachine = stateMachine;
                stateMachine = null;
                UnityEditor.EditorUtility.SetDirty(this);
            }
#endif
            for (int i = 0; i < controller.layers.Length; i++)
            {
                var layer = controller.layers[i];
                layer.LayerIndex = i;
                layer.stateMachine.Controller = controller;
                layer.stateMachine.Layer = layer;
                layer.stateMachine.OnScriptReload(this);
                layer.stateMachine.Id.Value = -1;
                for (int j = 0; j < layer.stateMachine.SubStateMachines.Length; j++)
                    layer.stateMachine.SubStateMachines[j].Id.Value = j;
                UpdateEditStateMachine(editStateMachineId);
            }
        }

        public virtual void UpdateEditStateMachine(int editStateMachineId)
        {
            this.editStateMachineId = editStateMachineId;
            var layer = controller.CurrLayer;
            if (editStateMachineId == -1)
                editStateMachine = layer.stateMachine;
            else if (editStateMachineId < layer.stateMachine.SubStateMachines.Length)
                editStateMachine = (StateMachine)layer.stateMachine.SubStateMachines[editStateMachineId];
        }

        public virtual void GetClipNames(Transform root, List<string> clipNames) { }

        public virtual float GetAnimClipLength(StateAction action) => 0f;
#endif
    }
}